<template>
  <el-dialog
      title="管理客户"
      :visible.sync="dialogVisible"
      :before-close="close"
      width="60%"
  >
    <div>
      <div class="flex-row-center">
        <el-form ref="queryCustomerForm" :model="queryParams" label-width="auto">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="客户名称">
                <el-input v-model="queryParams.customerName" placeholder="请输入客户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务类型">
                <el-select v-model="queryParams.businessScopeCode" placeholder="请选择业务类型" @change="handleQuery">
                  <el-option
                      v-for="item in businessTypes"
                      :key="item.code"
                      :label="item.label"
                      :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div style="margin-left: 15px">
                <el-button type="primary" @click.stop="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div>
        <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="list"
            :row-key="(row=>{return row.customerId})"
            :header-cell-style="{ background: '#FAFAFA', color: '#000000' }" border
            @select="selectItem"
            @select-all="selectAll">
          <template slot="empty">
            <el-empty :image-size="50" description="暂无客户信息"></el-empty>
          </template>
          <el-table-column
              key="customerId"
              type="selection"
              width="55"
              reserve-selection
          >
          </el-table-column>
          <el-table-column label="客户名称" align="center" prop="customerName" min-width="120px" show-overflow-tooltip/>
          <el-table-column label="联系方式" align="center" prop="customerPhone" min-width="120px" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="客户类型" align="center" prop="customerType" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">
              <dict-tag :options="dict.type.customer_type" :value="row.customerTypeCode"/>
            </template>
          </el-table-column>
          <!--                    <el-table-column label="客户来源" align="center" prop="customerSource" min-width="120px" show-overflow-tooltip>-->
          <!--                        <template v-slot="{row}">-->
          <!--                            <dict-tag :options="dict.type.customer_source" :value="row.customerSource"/>-->
          <!--                        </template>-->
          <!--                    </el-table-column>-->
        </el-table>
        <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>

        <div style="margin-top: 40px">
          <el-form ref="managerCustomerForm" :model="form" :rules="rules" label-width="80px">
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="说明" prop="content">
                  <el-input type="textarea" placeholder="请输入说明" v-model="form.content" maxlength="500" :rows="5" show-word-limit></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="附件">
                  <div class="flex">
                    <image-common info="上传附件" :limit="20" v-model="form.annex" :up-type="2"></image-common>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

      </div>

    </div>
    <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confimSelectedCustomer">确 定</el-button>
      </span>
  </el-dialog>
</template>

<script>
import {getCustomerList} from "@/api/memberManage/memberList";
import {contractTemplateManageCustomers, manageCustomersVerify} from "@/api/contractTemplate/contractTemplate"
import {contractTemplateOtherManageCustomers} from "@/api/contractTemplate/otherContractTemplate"
import {contractTemplateApplyManageCustomers} from "@/api/contractTemplate/templateUpdate";

export default {

  components: {},
  dicts: ['customer_type', 'customer_source'],
  props: {
    //0标准模版关联客户  1.其他合同模版关联客户 2.合同模版申请关联客户
    viewType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      businessTypes: [{
        label: '全业务客户',
        code: 1
      }, {
        label: '自营客户',
        code: 2
      }, {
        label: '渠道客户',
        code: 3
      }],
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        customerName: null,
        businessScopeCode: 1
      },
      form: {
        id: null,
        templateId: null,
        customerIds: null,
        content: null,
        annex: null,
      },
      rules: {
        content: [
          {required: true, message: '请输入说明', trigger: 'change'},
        ],
      },
      total: 0,
      list: [],
      checkList: [],
    }
  },
  computed: {},
  methods: {

    //id:模版申请专用id  templateId:关联的合同模版id customerIds:已关联的客户id(用于回显)
    show(id, templateId, customerIds) {
      this.form.content = null
      this.form.annex = null
      this.checkList = [];
      if (!this.isNull(id)) {
        this.form.id = id;
      }
      if (customerIds?.length > 0) {
        this.checkList = customerIds;
      }
      console.log('旧客户ids', this.checkList)
      this.form.templateId = templateId
      this.dialogVisible = true
      this.handleQuery()
    },
    getList() {
      this.loading = true
      getCustomerList(this.queryParams).then(res => {
        this.list = res.rows;
        this.total = res.total;
        this.$nextTick(() => {
          this.list.forEach(row => {
            if (this.checkList?.includes(row.customerId)) {
              this.$refs.multipleTable.toggleRowSelection(row, true)
            }
          })
        })
      }).finally(() => {
        this.loading = false
      })
    },

    close() {
      this.dialogVisible = false
      this.$refs.multipleTable.clearSelection();
    },
    resetQuery() {
      this.$refs?.queryCustomerForm?.resetFields()
      this.queryParams.customerName = null
      this.handleQuery()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    selectItem(selecteds, row) {
      if (!this.checkList.includes(row.customerId)) {
        // 回显数据里没有本条，把这条加进来(选中)
        this.checkList.push(row.customerId);
      } else {
        // 回显数据里有本条，把这条删除(取消选中)
        this.checkList.forEach((id, index) => {
          if (id === row.customerId) {
            this.checkList.splice(index, 1);
          }
        });
      }

    },
    selectAll(selecteds) {
      if (selecteds.length > 0) {
        selecteds.forEach(item => {
          if (!this.checkList.includes(item.customerId)) {
            this.checkList.push(item.customerId);
          }
        });
      } else {
        this.list.forEach(item => {
          this.checkList.forEach((id, index) => {
            if (id === item.customerId) {
              this.checkList.splice(index, 1);
            }
          });
        });

      }
    },
    // 确定
    confimSelectedCustomer() {
      console.log('checkList', this.checkList)
      this.form.customerIds = this.checkList;
      this.$refs['managerCustomerForm'].validate((valid) => {
        if (valid) {
          switch (this.viewType) {
            case 0://标准模版
              this.manageCustomersVerify()
              break
            case 1://其他合同模版
              contractTemplateOtherManageCustomers(this.form).then(res => {
                this.$emit('success')
                this.close()
              })
              break
            case 2://模版申请
              contractTemplateApplyManageCustomers(this.form).then(res => {
                this.$emit('success')
                this.close()
              })
              break
          }
        }
      })
    },
    // 标准模版管理客户前校验
    manageCustomersVerify() {
      manageCustomersVerify(this.form).then(res => {
        if (res.data) {
          this.standardTemplateManagerCustomer()
        } else {
          this.$confirm(res.msg, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.standardTemplateManagerCustomer()
          })
        }
      })
    },
    // 标准模版管理客户
    standardTemplateManagerCustomer() {
      contractTemplateManageCustomers(this.form).then(res => {
        this.$emit('success')
        this.close()
      })
    }

  },
  mounted() {

  },

}
</script>

<style lang="scss" scoped>
.queryView {
  position: relative;
  top: -8px;
  margin-left: 30px;
}
</style>
